<?php
class Tag extends AppModel {

	var $name = 'Tag';
	var $validate = array(
		'id' => array('numeric'),
		'name' => array('notempty')
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $hasAndBelongsToMany = array(
		'Article' => array(
			'className' => 'Article',
			'joinTable' => 'articles_tags',
			'foreignKey' => 'tag_id',
			'associationForeignKey' => 'article_id',
			'unique' => true,
			'conditions' => '',
			'fields' => 'Article.id,Article.title,Article.user_id',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'finderQuery' => '',
			'deleteQuery' => '',
			'insertQuery' => ''
		)
	);

	function saveTags($string = null){
		if($string){     
			$return = array();
			$this->name = 'Tag';
			$array = explode(',', $string);	//入力されたタグを,ごとに区切って配列化
			foreach($array as $tag){	
			 	if(!empty($tag)) {
					$this->data[$this->name]['name'] = trim($tag);
					$this->recursive = -1;

					if (empty($tag)) continue;
					
					// タグが存在するか
					$existing = $this->findByName($tag);

					if(!empty($existing)) {
						$return[] = $existing[$this->name][$this->primaryKey];
					} else { 
						// 存在しない場合タグをデーターベースに保存
						$this->id = null;
						if($this->save($this->data)) $return[] = $this->id;
					}
				}
			}
			return $return;
		}
		return null;
	}

	function popular() {
		return $this->query("SELECT `Tag`.`id`, `Tag`.`name`,  
						COUNT(articles_tags.article_id) as count 
	 					FROM `articles_tags` 
						JOIN `tags` as `Tag` ON `articles_tags`.`tag_id` = `Tag`.`id` 
						JOIN `articles` as `Article` ON `articles_tags`.`article_id` = `Article`.`id` 
						GROUP BY(tag_id) 
						ORDER BY RAND(),`Tag`.`name` ASC, `Article`.`viewed` DESC LIMIT 30");
		
	}

	function search($conditions = null) {
		if(!is_null($conditions)) {
			$db = &ConnectionManager::getDataSource($this->useDbConfig);
			$conditions = $db->conditions($conditions);
		}
		return $this->query("SELECT Article.id
	 					FROM `articles_tags` 
						JOIN `tags` as `Tag` ON `articles_tags`.`tag_id` = `Tag`.`id` 
						JOIN `articles` as `Article` ON `articles_tags`.`article_id` = `Article`.`id`
						{$conditions} GROUP BY(articles_tags.article_id)");
		
	}
}
?>